﻿using Abp.Application.Services;
using Abp.Authorization;
using Abp.Extensions;
using Abp.IdentityFramework;
using Abp.Localization;
using Abp.Runtime.Session;
using Microsoft.AspNetCore.Identity;
using Mt.Site.Core.Base.Authorization.Users;
using Mt.Site.Core.MultiTenancy;
using System;
using System.Threading.Tasks;

namespace Mt.Site.Application
{
    public abstract class MtSiteAppServiceBase : ApplicationService
    {
        public TenantManager TenantManager { get; set; }

        public UserManager UserManager { get; set; }

        protected MtSiteAppServiceBase()
        {
            LocalizationSourceName = MtSiteConsts.LocalizationSourceName;
        }

        protected virtual async Task<User> GetCurrentUserAsync()
        {
            var user = await UserManager.FindByIdAsync(AbpSession.GetUserId().ToString());
            if (user == null)
            {
                throw new Exception("There is no current user!");
            }

            return user;
        }

        protected virtual User GetCurrentUser()
        {
            var user = UserManager.GetUserOrNull(AbpSession.ToUserIdentifier());
            if (user == null)
            {
                throw new Exception("There is no current user!");
            }

            return user;
        }

        protected virtual Task<Tenant> GetCurrentTenantAsync()
        {
            using (CurrentUnitOfWork.SetTenantId(null))
            {
                return TenantManager.GetByIdAsync(AbpSession.GetTenantId());
            }
        }

        protected virtual Tenant GetCurrentTenant()
        {
            using (CurrentUnitOfWork.SetTenantId(null))
            {
                return TenantManager.GetById(AbpSession.GetTenantId());
            }
        }

        protected virtual void CheckErrors(IdentityResult identityResult)
        {
            identityResult.CheckErrors(LocalizationManager);
        }

        protected virtual async Task CheckPermission(string permissionName)
        {
            if (!permissionName.IsNullOrWhiteSpace() && ! (await IsGrantedAsync(permissionName)))
            {
                var permission = PermissionManager.GetPermissionOrNull(permissionName);
                if (permission != null)
                {
                    string localizedPermissionName;
                    if (permission.DisplayName != null && permission.DisplayName is LocalizableString)
                    {
                        var p = permission.DisplayName as LocalizableString;
                        localizedPermissionName = LocalizationManager.GetString(p.SourceName, p.Name);
                    }
                    else
                    {
                        localizedPermissionName = permissionName;
                    }

                    throw new AbpAuthorizationException(
                        $"Required permissions are not granted. At least one of these permissions must be granted: {localizedPermissionName}");
                }
                else
                {
                    throw new AbpAuthorizationException("Required permission does not exist");
                }
            }
        }
    }
}
